import { defineStore } from "pinia"
import { login } from '@/api/auth/index'
import { Session, Local } from "@/utils/storage"
import { RouteRecordRaw } from "vue-router"

export const Key = {
  rememberKey: 'isRemember',
  accessTokenKey: 'accessToken',
  userInfoKey: 'userInfo',
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => {
    return {
      rememberData: Local.get(Key.rememberKey),
      accessToken: Session.get(Key.accessTokenKey),
      userInfo: Local.get(Key.userInfoKey),
      buttonList: [] as string[], //按钮权限
      menuList: [] as string[], //菜单权限

    }
  },
  actions: {
    //记住密码
    setRememberPwd(data?: LoginData) {
      this.rememberData = data
      if (data) {
        Local.set(Key.rememberKey, data)
      } else {
        Local.remove(Key.rememberKey)
      }
    },

    // 登录操作
    userLogin(loginData: LoginData) {
      return new Promise((resolve, reject) => {
        login(loginData).then((res: any) => {
          const { data } = res
          const accessToken = data.access_token
          // console.log('accessToken', accessToken);
          this.accessToken = accessToken
          // 保存到session
          Session.set(Key.accessTokenKey, accessToken)
          resolve(res)
        }).catch((error) => {
          reject(error)
        })
      })
    },

    //设置用户信息
    setUserInfo(data: UserInfo) {
      this.userInfo = data
      Local.set(Key.userInfoKey, data)
    },

    // 设置按钮权限
    async setButtonList(data: string[]) {
      this.buttonList = data
    },

    // 设置菜单权限
    async setMenuList(data: RouteRecordRaw[]) {
      this.menuList = data
    },
  }
})